class Solution
{
public:
    int nearestValidPoint(int x, int y, vector<vector<int>> &points)
    {
        int result = -1;
        int minDistance = -1;
        for (int i = 0; i < points.size(); ++i)
        {
            auto &point = points[i];
            if (point[0] == x || point[1] == y)
            {
                if (result == -1)
                {
                    result = i;
                    minDistance = abs(x - point[0]) + abs(y - point[1]);
                }
                else
                {
                    int distance = abs(x - point[0]) + abs(y - point[1]);
                    if (distance < minDistance)
                    {
                        result = i;
                        minDistance = distance;
                    }
                }
            }
        }
        return result;
    }
};